<template>
    <div style="width: 98%">
        <el-form label-position="top" :model="formData" :rules="rules" ref="ruleForm">
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="计划时间:" prop="planYear">
                        <el-date-picker
                            style="margin-left: 10px; width: 100%"
                            v-model="formData.planYear"
                            type="year"
                            :clearable="false"
                            value-format="yyyy"
                            placeholder="选择时间"
                            @change="getPlanInfo"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="能耗类型" prop="energyTypeCode">
                        <el-select
                            v-model="formData.energyTypeCode"
                            filterable
                            placeholder="请选择"
                            transfer
                            style="width: 100%"
                            @change="getPlanInfo"
                        >
                            <el-option
                                v-for="item in energyplanOptions"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="isSubItemData">
                    <el-form-item label="选择分项：" prop="subitemId">
                        <el-tree-select
                            v-if="isShowTree"
                            style="width: 100%"
                            placeholder="请选择分项"
                            show-search
                            v-model="formData.subitemId"
                            :treeParams="subitemOptions"
                            @node-click="handleNodeClick"
                            :select-params="{
                                clearable: false,
                            }"
                            selectClass="customSelectTree"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="能源计划：" prop="totalPlanAmount">
                        <el-input
                            :placeholder="`能源计划不能小于${daysInYear}`"
                            v-model="formData.totalPlanAmount"
                            @blur="handleBlur"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="计划分配方式" prop="distributionTypeCode">
                        <el-radio-group v-model="formData.distributionTypeCode">
                            <el-radio
                                v-for="item in distributionList"
                                :label="item.code"
                                :key="item.code"
                                :value="item.code"
                                >{{ item.name }}</el-radio
                            >
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-table :data="tableData" border style="width: 100%" class="customTableClass">
            <el-table-column prop="planDate" label="时间" width="180" />
            <el-table-column prop="planAmount" :label="`能源计划 ${getUnit}`">
                <template slot-scope="{ row }">
                    <el-input
                        size="small"
                        v-show="isEdit"
                        placeholder="请输入"
                        v-model="row.planAmount"
                        oninput="value = value.replace(/[^0-9]/g, '');"
                        @blur="setTotalPlanAmount"
                    />
                    <span v-show="!isEdit">{{ row.planAmount }}</span>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>
<script>
    import dayjs from 'dayjs'
    import _ from 'lodash'
    import { mapGetters } from 'vuex'
    import signUpload from '@/components/signUpload'
    import { updateEnergyPlan, getEnergyPlanOne } from '@/api/energyplanMessage'
    import {
        findCityOptions,
        findEnergySelect,
        findProjectSubitemTreeByEnergyType,
        findEnumOptions,
    } from '@/api/common'
    const CUSTOM = 'custom'
    export default {
        components: {
            signUpload,
        },
        props: {
            title: String,
            rowData: Object,
        },
        computed: {
            ...mapGetters(['projectId']),
            isEdit() {
                return this.formData.distributionTypeCode === CUSTOM
            },
            getUnit() {
                const target = this.energyplanOptions.find(
                    (item) => item.code === this.formData.energyTypeCode
                )
                return target && target.unit ? `(${target.unit})` : ''
            },
        },
        data() {
            const rowData = this.rowData || {}
            const defaultTime = dayjs().format('YYYY')
            const startOfYear = dayjs(`${defaultTime}-01-01`).startOf('year')

            const timeStr = `${defaultTime}-12`
            const daysInMonth = dayjs(timeStr).daysInMonth()

            const endOfYear = dayjs(`${timeStr}-${daysInMonth}`).endOf('year')
            const daysInYear = endOfYear.diff(startOfYear, 'day') + 1
            return {
                isShowTree: true,
                daysInYear,
                formData: {
                    id: rowData?.id || '',
                    projectId: this.$store.state.projectId,
                    planYear: rowData?.planYear || defaultTime,
                    energyTypeCode: rowData?.energyTypeCode || '',
                    subitemId: rowData?.subitemId || '',
                    totalPlanAmount: rowData?.totalPlanAmount || '',
                    distributionTypeCode: rowData?.distributionTypeCode || CUSTOM,
                },
                rules: {
                    planYear: [{ required: true, message: '请选择计划时间', trigger: 'change' }],
                    energyTypeCode: [
                        { required: true, message: '请选择能源类型', trigger: 'change' },
                    ],
                    subitemId: [{ required: true, message: '请选择分项', trigger: 'change' }],
                    totalPlanAmount: [
                        { required: true, message: '请选择输入能源计划', trigger: 'change' },
                        { pattern: /^\d+$/, message: '请输入正整数', trigger: 'change' },
                        {
                            validator: (rule, value, callback) => {
                                if (value < daysInYear) {
                                    callback(new Error(`能源计划不能小于${daysInYear}`))
                                } else {
                                    callback()
                                }
                            },
                            trigger: 'change',
                        },
                    ],
                    distributionTypeCode: [
                        { required: true, message: '请选择计划分配方式', trigger: 'change' },
                    ],
                },
                tableData: [],
                energyplanOptions: [],
                distributionList: [],
                subitemOptions: {
                    data: [],
                    clickParent: true,
                    props: {
                        'node-key': 'id',
                        children: 'children',
                        label: 'name',
                        value: 'id',
                    },
                },
                isSubItemData: false,
            }
        },
        watch: {
            'formData.subitemId': {
                handler() {
                    this.getPlanInfo()
                },
                immediate: true,
            },
            'formData.energyTypeCode': {
                handler() {
                    this.isShowTree = false
                    if (this.formData.energyTypeCode) {
                        findProjectSubitemTreeByEnergyType({
                            projectId: this.formData.projectId,
                            energyType: this.formData.energyTypeCode,
                        }).then((resp) => {
                            this.isShowTree = true
                            this.subitemOptions.data = resp.data
                            this.isSubItemData = true
                            //this.$forceUpdate()
                        })
                    }
                },
                immediate: true,
            },
        },
        created() {
            this.hasParent = false
            this.initSetModal()
            this.initData()
        },
        methods: {
            initData() {
                findEnergySelect(this.$store.state.projectId).then(
                    (resp) => (this.energyplanOptions = resp.data)
                )
                findEnumOptions('energyPlanDistributionType').then(
                    (resp) => (this.distributionList = resp.data)
                )
            },
            getCity(value) {
                findCityOptions(value).then(
                    (resp) =>
                        (this.cityList = resp.data.map((item) => ({
                            name: item.key,
                            code: item.value,
                        })))
                )
            },
            handleBlur(event) {
                const value = event.target.value
                this.tableData = this.distributeInteger(value, 12)
            },
            distributeInteger(total, months) {
                const amountPerMonth = Math.floor(total / months)
                const remainder = total % months // 余数
                const distribution = []
                const { planYear } = this.formData
                for (let i = 0; i < months; i++) {
                    distribution.push({
                        planDate: `${planYear}-${this._padZero(i + 1)}`,
                        planAmount: amountPerMonth,
                    })
                }
                distribution[months - 1].planAmount += remainder
                return distribution
            },

            distributePlanAmount(data) {
                const result = []
                const { planDate, planAmount } = data
                const dateArr = planDate.split('-')
                const year = parseInt(dateArr[0])
                const month = parseInt(dateArr[1])
                const daysInMonth = dayjs(planDate).daysInMonth()
                const dailyAmount = Math.floor(planAmount / daysInMonth) // 每日平均分配的金额
                let remainder = planAmount % daysInMonth // 余数
                for (let i = 1; i <= daysInMonth; i++) {
                    const day = this._padZero(i)
                    const _month = this._padZero(month)
                    result.push({
                        planDate: `${year}-${_month}-${day} 00:00:00`,
                        planAmount: dailyAmount,
                    })
                }
                result[daysInMonth - 1].planAmount += remainder
                return result
            },

            transformTableMap(data) {
                return data.map((item) => ({
                    planDate: item.planDateStr,
                    planAmount: parseInt(item.planAmount),
                }))
            },
            _padZero(data) {
                return data < 10 ? '0' + data : data
            },
            handleNodeClick(value) {
                this.hasParent = value.parentId === '-1'
            },
            getPlanInfo() {
                const { planYear, projectId, energyTypeCode, subitemId } = this.formData
                const params = { projectId, subitemId, planYear, energyTypeCode }
                if (Object.values(params).every((value) => !!value)) {
                    params.subitemId = this.hasParent ? '' : subitemId
                    getEnergyPlanOne(params).then((resp) => {
                        const { code, data } = resp
                        if (code === 200 && data) {
                            this.formData.id = data.id
                            this.formData.totalPlanAmount = data.totalPlanAmount
                            this.tableData = this.transformTableMap(data.energyPlanDetailList || [])
                        }
                    })
                }
            },
            setTotalPlanAmount() {
                this.formData.totalPlanAmount = this.tableData.reduce(
                    (prev, next) => parseInt(prev || 0) + parseInt(next.planAmount || 0),
                    0
                )
            },
            submitForm() {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        let energyPlanDetailList = []
                        this.tableData.forEach((element) => {
                            energyPlanDetailList = [
                                ...energyPlanDetailList,
                                ...this.distributePlanAmount(element),
                            ]
                        })

                        const params = {
                            ...this.formData,
                            subitemId: this.hasParent ? '' : this.formData.subitemId,
                        }
                        params.energyPlanDetailList = energyPlanDetailList
                        updateEnergyPlan(params).then((resp) => {
                            const { code, msg } = resp
                            if (code === 200) {
                                this.$message.success(msg)
                                this.$emit('Close', true)
                            }
                        })
                    }
                })
            },

            initSetModal() {
                this.$emit('SetTitle', this.$props.title)
                this.$emit('SetPageWidth', 1200)
                this.$emit('SetPageActions', [
                    {
                        text: '取消',
                        theme: 'default',
                        handle: () => {
                            this.$emit('Close')
                        },
                    },
                    {
                        text: '保存',
                        theme: 'primary',
                        handle: () => {
                            this.submitForm()
                        },
                        loading: false,
                    },
                ])
            },
        },
    }
</script>

<style lang="scss" scoped>
    ::v-deep {
        .el-table {
            background: $table-bg;
            tr {
                background: $table-defalut-tr-bg;
            }
            .el-table__expand-icon {
                color: $table-search-text-color;
            }

            ::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
                background: $table-striped-bg;
            }
            ::v-deep .el-table::before,
            .el-table--group::after,
            .el-table--border::after {
                background-color: $table-before-line-color;
            }

            ::v-deep .el-table__fixed-right::before {
                background-color: $table-before-line-color;
            }
            ::v-deep .el-pagination__total {
                color: $table-pagination-total-color;
            }
            ::v-deep .el-pagination__jump {
                color: $table-pagination-total-color;
            }
            ::v-deep .el-table__fixed::before {
                background-color: $table-before-line-color;
            }
            ::v-deep .el-pagination button:disabled {
                background-color: $com-bg-color;
            }
            ::v-deep .el-pager li {
                background: $com-bg-color;
            }
        }
        .customTableClass {
            &::after,
            &::before {
                background-color: transparent !important;
            }
        }
    }
</style>
<style lang="scss">
    .customSelectTree {
        margin-left: 12px;
        .el-select {
            width: 100%;
        }
    }
</style>
